package homework.manager;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class StakeManager {
    private final Map<String, Map<String, Integer>> stakesByBetOffer = new ConcurrentHashMap<>();

    public void addStake(String betOfferId, String customerId, int stake) {
        stakesByBetOffer.computeIfAbsent(betOfferId, k -> new ConcurrentHashMap<>())
                        .put(customerId, Math.max(stake, stakesByBetOffer.get(betOfferId).getOrDefault(customerId, 0)));
    }

    public String getHighStakes(String betOfferId) {
        Map<String, Integer> stakes = stakesByBetOffer.getOrDefault(betOfferId, Collections.emptyMap());
        List<Map.Entry<String, Integer>> sortedStakes = new ArrayList<>(stakes.entrySet());
        sortedStakes.sort((e1, e2) -> e2.getValue().compareTo(e1.getValue()));
        return sortedStakes.stream()
                           .limit(20)
                           .map(e -> e.getKey() + "=" + e.getValue())
                           .reduce("", (a, b) -> a.isEmpty() ? b : a + "," + b);
    }
}
